using System;
using System.Collections.Generic;
using System.Collections;
using System.Web;
using System.Xml;
using ChannelVN.Cached.Common;
using System.Web.Caching;
using ChannelVN.Cached;

namespace ChannelVN.Cached.Config
{
    public class MetaRules : CollectionBase
    {
        private const string CACHE_NAME_FOR_META_SETTING_FILE = "COMMON_CONFIGURATION_META_SETTING";
        private const string CACHE_FORMAT_FOR_META_VALUE = "COMMON_CONFIGURATION_META_VALUE({0})";

        public long CacheExpired{get;set;}

        private static MetaRules _currentRules;

        public static MetaRules GetCurrentMetaRules()
        {
            if (Lib.IsWebApp)
            {
                object rules = HttpContext.Current.Cache[CACHE_NAME_FOR_META_SETTING_FILE];
                if (null == rules)
                {
                    try
                    {
                        string settingFilePath = HttpContext.Current.Server.MapPath(AppConfigs.MetaRuleSettingFile);
                        rules = LoadFile(settingFilePath);

                        CacheDependency fileDependency = new CacheDependency(settingFilePath);
                        HttpContext.Current.Cache.Insert(CACHE_NAME_FOR_META_SETTING_FILE, rules, fileDependency, DateTime.Now.AddSeconds((rules as MetaRules).CacheExpired), TimeSpan.Zero, CacheItemPriority.Normal, null);

                        return rules as MetaRules;
                    }
                    catch
                    {
                    }
                }
                else
                {
                    return rules as MetaRules;
                }
            }
            else
            {
                if (null == _currentRules)
                {
                    string settingFilePath = AppConfigs.MetaRuleSettingFile;
                    _currentRules = LoadFile(settingFilePath);
                }
                return _currentRules;
            }
            return new MetaRules();
        }
        private static MetaRules LoadFile(string filePath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filePath);

            MetaRules rules = new MetaRules();

            XmlNodeList nlstRules = xmlDoc.DocumentElement.SelectNodes("//rules/rule");

            for (int i = 0; i < nlstRules.Count; i++)
            {
                MetaRule rule = new MetaRule();
                rule.Name = nlstRules[i].Attributes["name"].Value;
                rule.CatId = nlstRules[i].SelectSingleNode("Cat_ID").InnerText;
                rule.Title = nlstRules[i].SelectSingleNode("Title").InnerText;
                rule.Kwd = nlstRules[i].SelectSingleNode("Description").InnerText;
                rule.Desc = nlstRules[i].SelectSingleNode("Keywords").InnerText;
                rule.DisplayUrl = nlstRules[i].SelectSingleNode("Display_Url").InnerText;

                rules.List.Add(rule);
            }

            XmlNode nodeFileSettingCacheExpire = xmlDoc.DocumentElement.SelectSingleNode("//Configuration/MetaRulesFile");
            rules.CacheExpired = Lib.Object2Long(nodeFileSettingCacheExpire.Attributes["cacheExpire"].Value);
            
            return rules;
        }

        public MetaRule this[int index]
        {
            get
            {
                return (MetaRule)List[index];
            }
        }

        public MetaRule this[string categoryId]
        {
            get
            {
                if (Lib.IsWebApp)
                {
                    List<MetaRule> rules = GetMathMeta(categoryId);
                    if (null != rules && rules.Count > 0)
                    {
                        return rules[0];
                    }
                }
                else
                {
                    for (int i = 0; i < List.Count; i++)
                    {
                        MetaRule rule = (MetaRule)List[i];
                        if (rule.CatId == categoryId)
                        {
                            return rule;
                        }
                    }
                }
                return null;
            }
        }

        public List<MetaRule> GetMathMeta(string catId)
        {
            string CacheName = string.Format(CACHE_FORMAT_FOR_META_VALUE, catId);
            List<MetaRule> lstObj;

            lstObj = CacheController.GetCacheDependencyInstance().Get(CacheName) as List<MetaRule>;
            if (lstObj == null)
            {
                lstObj = new List<MetaRule>();
                for (int i = 0; i < List.Count; i++)
                {
                    MetaRule rule = (MetaRule)List[i];
                    if (rule.CatId == catId)
                    {
                        lstObj.Add(new MetaRule(rule.Name, rule.CatId, rule.Title, rule.Kwd, rule.Desc, rule.DisplayUrl));
                    }
                }
                string configFilePath = HttpContext.Current.Server.MapPath(AppConfigs.MetaRuleSettingFile);
                CacheController.GetCacheDependencyInstance().Add(configFilePath, CacheName, lstObj);
            }
            return lstObj;
        }

        public class MetaRule
        {
            public string Name, CatId, Title, Kwd, Desc, DisplayUrl;
            public MetaRule()
            {
            }
            public MetaRule(string name, string catId, string title, string kwd, string desc, string displayUrl)
            {
                this.Name = name;
                this.CatId = catId;
                this.Title = title;
                this.Kwd = kwd;
                this.Desc = desc;
                this.DisplayUrl = displayUrl;
            }
        }
    }
}
